<?php
/**
 * Sfs  Controller plugin auth
 *
 * Sfs core Authentication
 *
 *
 * @version $Id: Auth.php 126 2010-04-19 08:24:20Z hami $
 * @license New BSD License
 * @uses Zend_Controller_Plugin_Abstract
 * @subpackage Controller Plugin
 */
class Sfs_Controller_Plugin_Auth extends  Zend_Controller_Plugin_Abstract
{
	private $_auth;
	private $_acl;

	private $_noauth = array('module' => 'core',
	'controller' => 'login',
	'action' => 'index');

	private $_noacl = array('module' => 'core',
	'controller' => 'login',
	'action' => 'noacl');

	private $_role;

	public function __construct( )
	{

//		if (defined('YET_INSTALL'))
//		return;
		// 取得認證資料
		$this->_auth = Zend_Auth::getInstance();
		// Use 'someNamespace' instead of 'Zend_Auth'
	//	$this->_auth->setStorage(new Zend_Auth_Storage_Session('Sfs'));


		$cache = Zend_Registry::get('cache');

		if(!$result = $cache->load('acl_cache')) {
			$this->_acl = new Sfs_Acl();
			$cache->save($this->_acl,'acl_cache');
		}
		else {
			$this->_acl =  $result;
		}
        Zend_Registry::set('acl',$this->_acl);
		//print_r($this->_acl);

	}

	public function routeStartup (Zend_Controller_Request_Abstract $request)
	{
	    //if (defined('YET_INSTALL'))
        //return;
        // 通過認證後,將自己加入 role
        // 預設角色為 guest

	    if( $this->_auth->hasIdentity() ) {
            $identity = $this->_auth->getIdentity();
            $role = $identity->username;
            //echo $role.'pppppppp';
            //echo '<pre>';print_r($this->_acl);
            if (!$this->_acl->hasRole($role))
            $groups  = $this->_acl->getUserGroup($role);

            $this->_acl->addRole( new Zend_Acl_Role($role),$groups);

        } else {
            $role = 'Guest';
        }
        $this->_role = $role;
	}

	public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
	{

		$controller = $this->_request->controller;

		$action = $this->_request->action;
		$module = $this->_request->module;
		$controller = $this->_request->controller;
		//echo $module;
		//$resource = $controller;
		//echo $module.'_'.$controller;
		$resource = null;
		if ($this->_acl->has($module.':'.$controller))
		$resource = $module.':'.$controller;
		elseif ($this->_acl->has($module)) {
			$resource = $module;
		}
        $params = array();
		if (!$this->_acl->isAllowed($this->_role, $resource, $action)) {
			//echo "$role -- $resource -- $action";
			if (!$this->_auth->hasIdentity()) {
				$module = $this->_noauth['module'];
				$controller = $this->_noauth['controller'];
				//$action = 'relogin';
				$action = $this->_noauth['action'];

			} else {
				$module = $this->_noacl['module'];
				$controller = $this->_noacl['controller'];
				$action = $this->_noacl['action'];
				//$action = 'relogin';//$this->_noacl['action'];
			}
		}

		$this->_request->setModuleName($module)
		->setControllerName($controller)
		->setActionName($action)
		->setDispatched( TRUE );

	}

}